<template>
    <div class="chatroom-container">
        <div class="chatroom-box">
          <div class="chat-right">
            <div class="list-top">
              <div class="drop-title">
                <img src="../assets/user.jpg" @click="showDropClick" >
                <div v-show="showDrop" class="drop-menu">
                  <span>退出登录</span>
                </div>
              </div>
              <span style="white-space:nowrap;text-overflow:ellipsis;">{{formItem.name}}</span>
            </div>
            <ul class="list-content">
              <li class="list-item active" v-for="item in otherUserList">
                <img src="../assets/group-icon.png" alt="">
                <span>{{item}}</span>
              </li>
            </ul>
          </div>
          <div class="chat-left">
             <!-- @mousedown="chatMove($event)" -->
            <div class="title-box">
              <span>{{formItem.roomId}}</span>
            </div>
            <div class="dialog-box">
              <div :class="item.class" v-for="item of dialogData">
                <img class="user-icon" src="../assets/group-icon.png" alt="">
                <ul>
                  <li>
                    <span>{{item.account}}</span>
                    <span>{{item.time}}</span>
                  </li>
                  <li>
                    <div v-if="item.dialog" class="message">{{item.dialog}}</div>
                    <div v-if="item.img_url" class="message" @click="showImg(item.img_url)">
                      <img style="width:40px;height:40px;" :src="item.img_url" alt="">
                    </div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="text-box">
              <textarea v-model="dialog" rows="3" class="textarea-input"></textarea>
              <div style="text-align:right;margin:10px;">
                <Button size="small" @click="openRoom">发起聊天</Button>
                <Button @click="postImage" size="small">发送图片文件</Button>
                <Button @click="postMessage" type="primary" size="small" style="margin-left: 8px">发送消息</Button>
              </div>
            </div>
          </div>
          <div class="videoContainer">
            <Button size="small" @click="openRoom">open</Button>
            <Button size="small" type="primary" @click="joinRoom">join</Button>
            <Button size="small" type="info" @click="leaveRoom">leave</Button>
            <div id="videos-container"></div>
          </div>
        </div>
    </div>
</template>

<script>
export default {
  props:['socket','formItem','message','userList','chatImgUrl'],
  data() {
    return {
        // 聊天室相关
        showLogin:true,
        dialog:'',
        dialogData:[],
        otherUserList:[],
        showDrop:false,
        connection:null
    }
  },
  mounted(){
    this.videoFun()
  },
  watch:{
    message:{//深度监听，可监听到对象、数组的变化
      handler(){
        this.getMessage(this.message)
        this.scrollToBottom()
      },
      deep:true
    },
    userList:{//深度监听，可监听到对象、数组的变化
      handler(){
        for(let i of this.userList){
          if(this.formItem.name!=i){
            this.otherUserList.push(i)
          }
        }
      },
      deep:true
    },
    chatImgUrl:{
      handler(){
        let data = {img_url: this.chatImgUrl,type:"send_img"};
        this.socket.emit("message",data);
      },
      deep:true
    }
  },
  methods: {
    showDropClick(){
      this.showDrop=!this.showDrop
    },
    // 登录按钮
    jumpToaChat(){
      if(this.formItem.account&&this.formItem.password){
        this.showLogin=false;
      }
    },
    //发送消息按钮
    postMessage(){
      if(this.dialog){
        //发送消息
        let data = {content: this.dialog,type:"send_txt"};
        this.socket.emit("message",data);
        this.dialog=''
      }else{
        console.log('输入框不能为空')
      }
    },
    // 发送图片消息
    postImage(){
      //发送消息
      this.$store.commit("imgBtnClick",true);
    },
    // //监听获取消息
    getMessage(msg){
      //房间其他人接收消息
      let moment = require('moment');
      let time = moment().format('HH:mm:ss');
      let data={}
      if(msg.info.sender==this.formItem.name){
        data={
          class: 'post-message',
          userSrc: '../assets/user.jpg',
          time: time,
          account: msg.info.sender,
        }
        if(msg.info.type=='send_txt'){
          data.dialog=msg.info.content
        }else if(msg.info.type=='send_img'){
          data.img_url=msg.info.img_url
        }
      }else{
        data={
          class: 'get-message',
          userSrc: '../assets/user.jpg',
          time: time,
          account: msg.info.sender,
        }
        if(msg.info.type=='send_txt'){
          data.dialog=msg.info.content
        }else if(msg.info.type=='send_img'){
          data.img_url=msg.info.img_url
        }
      }
      this.dialogData.push(data)
    },
    //窗口移动事件
    chatMove(e){
      let  x = e.clientX;	//鼠标位于屏幕的left
      let  y = e.clientY;	//鼠标位于屏幕的top
      let  sT = e.offsetX;
      let  sL = e.offsetY;
      var lay=$('.chatroom-container');
        //绑定鼠标移动事件
        lay.bind("mousemove",function(e){
            let eX = e.clientX;	//鼠标位于屏幕的left
            let eY = e.clientY;	//鼠标位于屏幕的top
            let lessX = eX - x;	//距初始位置的偏移量
            let lessY = eY - y;	//距初始位置的偏移量
            let _t = sT + lessX-120; //减120，加100，是由于定位给影响了，具体没发现规律，
            let _l = sL + lessY+100;
            if(_t<0){
                _t=0;
            }
            $('.chatroom-box').css({
                left:_t+'px',
                top:_l+'px'
            });
        })
        //绑定鼠标抬起事件
        lay.bind("mouseup",function(){
            $(this).unbind("mousemove");
        });
    },
    // 让滚动条始终保持在最下面
    scrollToBottom(){
      this.$nextTick(() => {
	    var container = this.$el.querySelector(".dialog-box");
        container.scrollTop = container.scrollHeight;
      })
    },
    //点击图片在画板上显示图片
    showImg(url){
      this.$store.commit("changeImg",url);
    },
    // 视频相关
    videoFun(){
      this.connection = new RTCMultiConnection();
      this.connection.socketURL = 'https://www.bim520.cn:8089/';

      this.connection.socketMessageEvent = 'audio-video-file-chat-demo';

      this.connection.enableFileSharing = true; // by default, it is "false".
      this.connection.session = {
          audio: true,
          video: true,
          data: true
      };
      this.connection.sdpConstraints.mandatory = {
          OfferToReceiveAudio: true,
          OfferToReceiveVideo: true
      };
      this.connection.videosContainer = document.getElementById('videos-container');
      var that=this;
      this.connection.onstream = function(event) {
        event.mediaElement.removeAttribute('src');
        event.mediaElement.removeAttribute('srcObject');
        var video = document.createElement('video');
        video.controls = true;
        if(event.type === 'local') {
            video.muted = true;
        }
        video.srcObject = event.stream;
        var width = parseInt(that.connection.videosContainer.clientWidth)-20;
        var mediaElement = getMediaElement(event.mediaElement, {
            title: event.userid,
            buttons: ['full-screen'],
            width: width,
            showOnMouseEnter: false
        });
        console.log(mediaElement)
        that.connection.videosContainer.appendChild(mediaElement);
        setTimeout(function() {
            mediaElement.media.play();
        }, 5000);
        mediaElement.id = event.streamid;
      };

      this.connection.onstreamended = function(event) {
          var mediaElement = document.getElementById(event.streamid);
          if(mediaElement) {
              mediaElement.parentNode.removeChild(mediaElement);
          }
      };
      console.log(this.connection)
    },
    openRoom(){
      this.connection.open(this.formItem.roomId, (isRoomOpened, roomid, error)=> {
          if(error) {
              alert(error);
          }
          if(isRoomOpened === true) {
              alert('Successfully created the room.');
          }
      })
    },
    joinRoom(){
      this.connection.join(this.formItem.roomId, function(isJoined, roomid, error) {
          if(isJoined === false) {
              alert(error); // maybe room doesn't exist or room is full or password is invalid
          }
          else {
              alert('Successfully joined the room.');
          }
      });
    },
    leaveRoom(){
      if(this.connection.isInitiator) {
          this.connection.closeEntireSession(function() {
            console.log('Entire session has been closed.')
          });
      }
      else {
        this.connection.leave();
      }
    }
  }
}
</script>

<style scoped lang='scss'>
// 聊天室
.chatroom-container{
    width:50%;
    height:100%;
    border:1px solid #ddd;
    background-color: #eee;
    position:relative;
    // display: flex;
    // justify-content: center;
    // align-items: center;
    .chatroom-box{
      position:absolute;
      top:100px;
      left:50px;
      border:1px solid #333;
      width:600px;
      height:400px;
      display: flex;
      justify-content: flex-start;
      background-color:#fff;
      .chat-right{
        width:120px;
        height:100%;
        background-color: #2E3238;
        color:#fff;
      }
      .chat-left{
        width:360px;
        height:100%;
        border:1px solid #333;
        // 标题
        .title-box{
          width:100%;
          height:30px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-bottom: 1px solid #000;
          span{
            font-size: 16px;
          }
        }
        // 对话框
        .dialog-box{
          width:100%;
          height:270px;
          border-bottom: 1px solid #000;
          overflow-y: auto; 
        }
      }
    }
  .list-top,.list-item,.active{
    padding:10px;
    img{
      width:30px;
      height:30px;
      border-radius: 50%;
      vertical-align: middle;
      margin-right:10px;
    }
  }
  .list-content{
    overflow-y: auto;
  }
  .list-content .active{
    background-color: #3A3F45;
  }
  // 公共
  .get-message,.post-message{
    padding:5px;
    .message:before{
      content: "";
      display: block;
      position: absolute;
      border:5px solid transparent;
    }
  }
  // 获得消息样式
  .get-message{
    text-align: left;
    display: flex;
    justify-content: flex-start;
    .message{
      background-color: #ACD9F8;
    }
    .message:before{
      top:8px;
      left:-10px;
      border-right-color:#ACD9F8;
    }
    .user-icon{
      margin-right:10px;
    }
  }
  // 发送消息样式
  .post-message{
    text-align: right;
    display: flex;
    justify-content: flex-start;
    flex-direction: row-reverse;
    .message{
      background-color: #B2E281;
    }
    .message:before{
      top:8px;
      right:-10px;
      border-left-color:#B2E281;
    }
    .user-icon{
      margin-left:10px;
    }
  }
  .message{
    border:1px solid #eee;
    border-radius: 8px;
    padding:8px;
    max-width: 300px;
    min-width: 10px;
    word-wrap:break-word;
    display: inline-block;
    position:relative;
    text-align: left;
  }
  .user-icon{
    width:30px;
    height:30px;
    border-radius:10px;
  }
  .textarea-input{
    width:100%;
    font-size:12px;
    overflow-y: auto;
  }
  .list-top{
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .drop-title{
    position:relative;
  }
  .drop-menu{
    position: absolute;
    left:0;
    top:32px;
    padding:8px;
    border-radius: 8px;
    color:#000;
    background-color: #fff;
    width:60px;
    text-align:center;
    cursor: default;
  }
  // 视频区域
  .videoContainer{
    border:1px solid #ddd;
    width:200px;
    height:400px;
  }
}
</style>
